home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Interactive Reference Guide / C-C++ Interactive Reference Guide.iso / c_ref / clesson / clesson.dir / 00015_Field_15.txt < prev    next >
Text File  |  1995-04-04  |  23KB  |  588 lines

  1.  
  2.                                   Lesson 2
  3.  
  4.                         Data Storage Concepts.
  5.  
  6.         It has been stated that "data + algorithms = programs".
  7.         This Lesson deals with with the first part of the addition sum.
  8.  
  9.   All information in a computer is stored as numbers represented using the binary number system. The information may be either program instructions or data elements. The latter are further subdivided into several different types,
  10. and stored in the computer's memory in different places as directed by the
  11. storage class used when the datum element is defined.
  12.  
  13. These types are:
  14.  
  15.   
  16.  
  17.  
  18. a) The Character.
  19.  
  20.      This is a group of 8 data bits and in 'C' represents either
  21.      a letter of the Roman alphabet, or a small integer in the range of 0
  22.      through to +255. So to arrange for the compiler to give you a namedmemory area in which to place a single letter you would "say":
  23.  
  24.   char letter;
  25.  
  26.      at the beginning of a program block. You should be aware that
  27.  whether or not a char is signed or unsigned is dependant
  28.  on the design of the processor underlying your compiler.
  29.  In particular, note that both the PDP-11, and VAX-11 made by
  30.  Digital Equipment Corporation have automatic sign extention of
  31. char. This means that the range of char is from -128 through to 
  32.  
  33.  
  34.  
  35. +127on these machines. Consult your hardware manual, there may beother exceptions to the trend towards unsigned char as the
  36. default.
  37.  
  38. This test program should clear things up for you.
  39.  
  40. /* ----------------------------------------- */
  41.  
  42. #ident "@(#) - Test char signed / unsigned.";
  43.  
  44. #include <stdio.h>
  45.  
  46. main()
  47. {
  48.         char a;
  49.         unsigned char b;
  50.  
  51.         
  52.  
  53. a = b = 128;
  54.         a >>= 1;
  55.         b >>= 1;
  56.   printf ( "\nYour computer has %ssigned char.\n\n", a == b ? "un" : "" );
  57.         }
  58.  
  59. /* ----------------------------------------- */
  60.  
  61.      Here ( Surprise! Surprise! ) is its output on a machine which has
  62.                  unsigned chars.
  63.  
  64. Your computer has unsigned char.
  65.  
  66.     Cut this program out of the news file. Compile and execute it on
  67.                 your computer in order to find out if you have signed or
  68. unsigned char.
  69.  
  70.   b) The Integers.
  71.  
  72.      As you might imagine this is the storage type in which to store wholenumbers. There are two sizes of integer which are known as short and long.The actual number of bits used in both of these types is ImplementationDependent. This is the way the jargonauts say that it varies from computerto computer. Almost all machines with a word size larger than sixteen bitshave the the long int fitting exactly into a machine word anda short intrepresented by the contents of half a word. It's done this way because
  73. most machines have instructions which will perform arithmetic
  74. efficientlyon both the complete machine word as well as the half-word.
  75. For thesixteen bit machines, the long integer is two machine words
  76. long,and the short integer is one.
  77.  
  78.   short int smaller_number;
  79.   long int big_number;
  80.  
  81.  
  82.  
  83.      Either of the words short or long may be omitted as a default is
  84.                  provided by the compiler. Check your compiler's documentationto seewhich default you have been given. Also you should be aware
  85. that somecompilers allow the you to arrange for the integers declaredwith justthe word "int" to be either short or long. The range for ashort int ona small computer is -32768 through to +32767, and for a long
  86. int -4294967296 through to +4294967295.
  87.  
  88.   c) The Real Numbers.
  89.  
  90.      Sometimes known as floating point numbers this number representationallows us to store values such as 3.141593, or -56743.098. So, usingpossible examples from a ship design program you declare floats anddoubles like this:
  91.  
  92.  
  93.  
  94.   float length_of_water_line;     /* in meters */
  95.   double displacement;            /* in grammes */
  96.  
  97.      In the same way that the integer type offers two sizes so does the
  98.      floating point representation. They are called float and double. Taking
  99.      the values from the file /usr/include/values.h the ranges which can be
  100.      represented by float and double are:
  101.  
  102.   MAXFLOAT      3.40282346638528860e+38
  103.   MINFLOAT      1.40129846432481707e-45
  104.   MAXDOUBLE     1.79769313486231470e+308
  105.   MINDOUBLE     4.94065645841246544e-324
  106.  
  107.      
  108.  
  109.  
  110. However you should note that for practical purposes the maximum
  111. number of significant digits that can be represented by a
  112. floatis approximately six and that by a double is twelve. Also you
  113. shouldbe aware that the above numbers are as defined by the IEEEfloatingpoint standard and that some older machines and compilers donotconform. All small machines bought retail will conform. If youare in doubt I suggest that refer to your machine's documentationfor the whole and exact story!
  114.  
  115.  
  116.   d) Signed and unsigned prefixes.
  117.  
  118.      For both the character and integer types the declaration can be preceded by the word "unsigned". This shifts the range so that
  119. 0  is the minimum, and the maximum is twice that of the signed
  120. dat  type in question. It's useful if you know that it is
  121.  
  122.  
  123.  
  124. impossible  for the number to go negative. Also if the word in memory is  going  to be used as a bit pattern or a mask and not a number the useof  unsigned is strongly urged. If it is possible for the sign bit in the bit pattern to be set and the program calls for the bit pattern  to be shifted to the right, then you should be aware that the sign bit will be extended if the variable is not declared unsigned. The default for the "int" types is always "signed", and, as
  125. discussed  above that of the "char" is machine dependent.
  126.  
  127.   This completes the discussion on the allocation of data types, except to  say that we can, of course, allocate arrays of the simple types simply by  adding a pair of square brackets enclosing a number which is the size of  the array after the variable's name:
  128.  
  129.   char client_surname[31];
  130.  
  131.  
  132.  
  133.  
  134.  This declaration reserves storage for a string of 30 characters plus the NULL character of value zero which terminates the string.
  135.  
  136.   Structures.
  137.  
  138.          Data elements which are logically connected, for example - to use the  example alluded to above - the dimensions and other details about a  sea  going ship, can be collected together as a single data unit called a  struct. One possible way of laying out the struct in the source code is:
  139.  
  140. struct ship          /* The word "ship" is known as the structure's "tag". */
  141. {
  142.   
  143.  
  144.  
  145.  
  146. char name[30];
  147.   double displacement;                           /* in grammes */
  148.   float length_of_water_line;                    /* in meters */
  149.   unsigned short int number_of_passengers;
  150.   unsigned short int number_of_crew;
  151.   };
  152.  
  153.      Note very well that the above fragment of program text does NOT   allocate any storage, it merely provides a named template to
  154. the  compiler so that it knows how much storage is needed for the   structure. The actual allocation of memory is done either like
  155. this:
  156.  
  157. struct ship cunarder;  Or by putting the name of the struct variable between the "}" and   the ";" on the last line of the definition. Personally I don't   use this method as I find that the letters of the name tend to get "lost" in the - shall we say - amorphous mass of characters  which  make up the definition itself.
  158.  
  159.  
  160.  
  161.  
  162.  
  163.  
  164.      The individual members of the struct can have values assigned to  them in this fashion:
  165.  
  166.   cunarder.displacement = 97500000000.0;
  167.   cunarder.length_of_water_line = 750.0
  168.   cunarder.number_of_passengers = 3575;
  169.   cunarder.number_of_crew = 4592;
  170.  
  171.      These are a couple of files called demo1.c & demo1a.c which contain   small 'C' programs for you to compile. So, please cut them out  of the  news posting file and do so.
  172.  
  173.  
  174.  
  175.  
  176.  
  177.  
  178.  
  179.  
  180. ----------------------------------------------------------------------
  181. #ident demo1.c  /* If your compiler complains about this line, chop it    
  182.                               out */
  183.  
  184. #include <stdio.h>
  185.  
  186. struct ship
  187. {
  188.   char name[31];
  189.   double displacement;                              /* in grammes */
  190.   float length_of_water_line;                       /* in meters */
  191.   unsigned short int number_of_passengers;
  192.   unsigned short int number_of_crew;
  193.   };
  194.  
  195.  
  196.  
  197.  
  198. char *format = "\
  199. Name of Vessel: %-30s\n\
  200.   Displacement: %13.3f\n\
  201.     Water Line: %5.1f\n\
  202.     Passengers: %4d\n\
  203.           Crew: %4d\n\n";
  204.  
  205. main()
  206. {
  207.   struct ship cunarder;
  208.  
  209.   cunarder.name = "Queen Mary";               /* This is the bad line. */
  210.   cunarder.displacement = 97500000000.0;
  211.   cunarder.length_of_water_line = 750.0
  212.   cunarder.number_of_passengers = 3575;
  213.   cunarder.number_of_crew = 4592;
  214.  
  215.  
  216.  
  217.  
  218.  
  219.  
  220.  printf ( format,
  221.            cunarder.name,
  222.                  cunarder.displacement,
  223.            cunarder.length_of_water_line,
  224.            cunarder.number_of_passengers,
  225.            cunarder.number_of_crew
  226.            );
  227.   }
  228.  
  229. ----------------------------------------------------------------------
  230.  
  231.   
  232.  
  233.  
  234.  
  235.  
  236.  
  237.  
  238.  
  239.  
  240.  
  241.                Why is the compiler complaining at line 21?
  242.      Well C is a small language and doesn't have the ability to allocate  strings to variables within the program text at run-time. This   program shows the the correct way to copy the string "Queen  Mary",  using a library routine, into the structure.
  243. ----------------------------------------------------------------------
  244. #ident demo1a.c  /* If your compiler complains about this line, chop 
  245.  
  246.                                 it out */
  247.  
  248. #include <stdio.h>
  249.  
  250. /*
  251. ** This is the template which is used by the compiler so that
  252. ** it 'knows' how to put your data into a named area of memory.
  253. */
  254.  
  255.  
  256.  
  257. struct ship
  258. {
  259.   char name[31];
  260.   double displacement;                              /* in grammes */
  261.   float length_of_water_line;                       /* in meters */
  262.   unsigned short int number_of_passengers;
  263.   unsigned short int number_of_crew;
  264.   };
  265.  
  266. /*
  267. ** This character string tells the printf() function how it is to output
  268. ** the data onto the screen. Note the use of the \ character at the end
  269. ** of each line. It is the 'continue the string on the next line' flag
  270. ** or escape character. It MUST be the last character on the line.
  271. ** This technique allows you to produce nicely formatted reports with all the
  272.  
  273.  
  274.  
  275. ** ':' characters under each other, without having to count the characters
  276. ** in each character field.
  277. */
  278.  
  279. char *format = "\n\
  280. Name of Vessel: %-30s\n\
  281.   Displacement: %13.1f grammes\n\
  282.     Water Line: %5.1f metres\n\
  283.     Passengers: %4d\n\
  284.           Crew: %4d\n\n";
  285.  
  286. main()
  287. {
  288.   struct ship cunarder;
  289.  
  290.   
  291.  
  292. strcpy ( cunarder.name, "Queen Mary" );           /* The corrected line */
  293.   cunarder.displacement = 97500000000.0;
  294.   cunarder.length_of_water_line = 750.0;
  295.   cunarder.number_of_passengers = 3575;
  296.   cunarder.number_of_crew = 4592;
  297.  
  298.   printf ( format,
  299.            cunarder.name,
  300.                                  cunarder.displacement,
  301.            cunarder.length_of_water_line,
  302.            cunarder.number_of_passengers,
  303.            cunarder.number_of_crew
  304.                                  );
  305.   }
  306.  
  307. ----------------------------------------------------------------------
  308.  
  309.      
  310.  
  311. I'd like to suggest that you compile the program demo1a.c and execute it.
  312.  
  313. $ cc demo1a.c
  314. $ a.out
  315.  
  316. Name of Vessel: Queen Mary
  317.   Displacement: 97500000000.0 grammes
  318.     Water Line: 750.0 metres
  319.     Passengers: 3575
  320.           Crew: 4592
  321.  
  322.      Which is the output of our totally trivial program to demonstrate
  323.      the use of structures.
  324.  
  325.  
  326.  
  327.  
  328.  
  329.  
  330.   Tip:
  331.  
  332.      To avoid muddles in your mind and gross confusion in other minds remember that you should ALWAYS declare a variable using a name which is  long enough to make it ABSOLUTELY obvious what you are talking about.
  333.  
  334.         Storage Classes.
  335.  
  336.         The little dissertation above about the storage of variables was   concerned with the sizes of the various types of data. There is  just the little matter of the position in memory of the variables'
  337.  storage.
  338.  
  339.      
  340.  
  341.  
  342.  
  343.    'C' has been designed to maximise the the use of memory by allowing you  to re-cycle it automatically when you have finished with it.
  344.         A variable defined in this way is known as an 'automatic' one. Although this is the default behaviour you are allowed to put the word 'auto' in  front of the word which states the variable's type in the definition.
  345.         It is quite a good idea to use this so that you can remind yourself  that this variable is, in fact, an automatic one. There are three other storage allocation methods, 'static' and 'register', and 'const'.
  346.         The 'static' method places the variable in main storage for the whole  of the time your program is executing. In other words it kills the  're-cycling' mechanism. This also means that the value stored there  is also available all the time. The 'register' method is very machine   and implementation dependent, and also perhaps somewhat archaic in  that the optimiser phase of the compilation
  347.  
  348.  
  349.  
  350.  process does it all for  you. For the sake of completeness I'll explain. Computers have a small  number of places to store numbers which can be accessed very quickly.
  351.         These places are called the registers of the Central Processing Unit.
  352.         The 'register' variables are placed in these machine registers instead of  stack or main memory. For program segments which are tiny loops the speed  at which your program executes can be enhanced quite remarkably.
  353.         The optimiser compilation phase places as many of your variables into registers as it can. However no machine can decide which of the  variables  should be placed in a register, and which may be left in memory, so if  your program has many variables and two or three should be register  ones  then you should specify which ones the compiler.
  354.  
  355.        
  356.  
  357.  All this is dealt with at much greater detail later in the course.
  358.  
  359.         Pointers.
  360.  
  361.         'C' has the very useful ability to set up pointers. These are memory  cells which contain the address of a data element. The variable name is   preceeded by a '*' character. So, to reserve an element of type char  and  a pointer to an element of type char, one would say.
  362.  
  363. char c;
  364. char *ch_p;
  365.  
  366.   I always put the suffix '_p' on the end of all pointer variables
  367.   simply so that I can easily remember that they are in fact pointers.
  368.  
  369.         
  370.  
  371.  
  372. There is also the companion unary operator '&' which yields the
  373.  address of the variable. So to initialize our pointer ch_p to point
  374.         at the char c, we have to say.
  375.  
  376.   ch_p = &c;
  377.  
  378.   Note very well that the process of indirection can procede to any
  379.         desired depth, However it is difficult for the puny brain of a normal
  380.         human to conceptualize and remember more that three levels! So be
  381. careful
  382.         to provide a very detailed and precise commentry in your program if
  383.         you put more than two or three stars.
  384.  
  385.  
  386.   Getting data in and out of your programs.
  387.  
  388.         As mentioned before 'C' is a small language and there are no intrinsic operators to either convert between binary numbers and ascii characters or to transfer information to and fro between the  computer's memory and the peripheral equipment, such as terminals or disk stores.
  389.  
  390.         This is all done using the i/o functions declared in the file stdio.h  which you should have examined earlier. Right now we are going to look  at the functions "printf" and "scanf". These two functions together  with their derivatives, perform i/o to the stdin and stdout files,  i/o to nominated files, and internal format conversions. This means  the conversion of data from ascii character strings to binary numbers  and vice versa completely within the computer's memory. It's more  efficient to set up a line of print inside memory and then to send the
  391.        
  392.  
  393.  
  394.  whole line to the printer, terminal, or whatever, instead of
  395.         "squirting" the letters out in dribs and drabs!
  396.  
  397.         Study of them will give you understanding of a very convenient way to  talk to the "outside world".
  398.  
  399.         So, remembering that one of the most important things you learn in  computing is "where to look it up", lets do just that.
  400.         If you are using a computer which has the unix operating system,   find your copy of the "Programmer Reference Manual" and turn to the  page printf(3S), alternatively, if your computer is using some other   operating system, then refer to the section of the documentation which  describes the functions in the program library.
  401.  
  402.        
  403.  
  404.  
  405.  
  406.  You will see something like this:-
  407.  
  408.         NAME
  409.                                 printf, fprintf, sprintf - print formatted
  410. output.
  411.  
  412.         SYNOPSIS
  413.                                 #include <stdio.h>
  414.  
  415.                                 int printf ( format [ , arg ] ... )
  416.                                 char *format;
  417.  
  418.                                 int fprintf ( stream, format [ , arg ] ... )
  419.                                 FILE *stream;
  420.                                 char *format;
  421.  
  422.  
  423.  
  424.  
  425.                                 int sprintf ( s, format [ , arg ] ... )
  426.                                 char *s, *format;
  427.  
  428.         DESCRIPTION
  429.  
  430.                                 etc... etc...
  431.  
  432.         The NAME section above is obvious isn't it?
  433.  
  434.         The SYNOPSIS starts with the line #include <stdio.h>. This tells  you that you MUST put this #include line in your 'C' source code   before you mention any of the routines. The rest of the paragraph  tells you how to call the routines. The " [ , arg ] ... " heiroglyph  in effect says that you may have as many arguments here as you wish,  but that you need not have any at all.
  435.  
  436.   
  437.  
  438.  
  439.  
  440.  
  441. The DESCRIPTION explains how to use the functions.
  442.  
  443.         Important Point to Note:
  444.  
  445.         Far too many people ( including the author ) ignore the fact that  the printf family of functions return a useful number which can be used to check that the conversion has been done correctly, and that  the i/o operation has been completed without error.
  446.  
  447.   Refer to the format string in the demonstration program above for
  448.         an example of a fairly sophisticated formatting string.
  449.  
  450.   In order to fix the concepts of printf in you mind, you
  451.         might care to write a program which prints some text in three ways:
  452.  
  453.  
  454.  
  455.  
  456.  
  457.  
  458. a) Justified to the left of the page. ( Normal printing. )
  459. b) Justified to the right of the page.
  460. c) Centred exactly in the middle of the page.
  461.  
  462.         Suggestions and Hint.
  463.  
  464.         Set up a data area of text using the first verse of "Quangle" as data.
  465.         Here is the program fragment for the data:-
  466.  
  467. /* ----------------------------------------- */
  468.  
  469.  
  470.  
  471.  
  472.  
  473.  
  474.  
  475.  
  476. char *verse[] =
  477. {
  478.   "On top of the Crumpetty Tree",
  479.   "The Quangle Wangle sat,",
  480.   "But his face you could not see,",
  481.   "On account of his Beaver Hat.",
  482.   "For his Hat was a hundred and two feet wide.",
  483.   "With ribbons and bibbons on every side,",
  484.   "And bells, and buttons, and loops, and lace,",
  485.   "So that nobody ever could see the face",
  486.   "Of the Quangle Wangle Quee.",
  487.   NULL
  488.   };
  489.  
  490. /* ----------------------------------------- */
  491.  
  492.  
  493.  
  494.   Cut it out of the news file and use it in a 'C' program file called
  495.         verse.c
  496.  
  497.         Now write a main() function which uses printf alone for (a) & (b)
  498.         You can use both printf() and sprintf() in order to create
  499.         a solution for (c) which makes a good use of the capabilities
  500.         of the printf family. The big hint is that the string controlling
  501.         the format of the printing can change dynamically as program execution  proceeds. A possible solution is presented in the file verse.c which is  appended here. I'd like to suggest that you have a good try at making  a program of you own before looking at my solution.
  502.         ( One of many I'm sure )
  503.  
  504. /* ----------------------------------------- */
  505.  
  506.  
  507.  
  508. #include <stdio.h>
  509.  
  510. char *verse[] =
  511. {
  512.   "On top of the Crumpetty Tree",
  513.   "The Quangle Wangle sat,",
  514.   "But his face you could not see,",
  515.   "On account of his Beaver Hat.",
  516.   "For his Hat was a hundred and two feet wide.",
  517.   "With ribbons and bibbons on every side,",
  518.   "And bells, and buttons, and loops, and lace,",
  519.   "So that nobody ever could see the face",
  520.   "Of the Quangle Wangle Quee.",
  521.   NULL
  522.   };
  523.  
  524.  
  525.  
  526. main()
  527. {
  528.         char **ch_pp;
  529.  
  530.         /*
  531.         ** This will print the data left justified.
  532.         */
  533.  
  534.         for ( ch_pp = verse; *ch_pp; ch_pp++ ) printf ( "%s\n", *ch_pp );
  535.         printf( "\n" );
  536.         /*
  537.         ** This will print the data right justified.
  538.         **
  539.         **  ( As this will print a character in column 80 of
  540.         **    the terminal you should make sure any terminal setting
  541.         **    which automatically inserts a new line is turned off. )
  542.         */
  543.  
  544.         for ( ch_pp = verse; *ch_pp; ch_pp++ ) printf ( "%79s\n", *ch_pp );
  545.         printf( "\n" );
  546.  
  547.         /*
  548.         ** This will centre the data.
  549.         */
  550.  
  551.         for ( ch_pp = verse; *ch_pp; ch_pp++ )
  552.         {
  553.                 int length;
  554.                 char format[10];
  555.  
  556.                 length = 40 + strlen ( *ch_pp ) / 2;      /* Calculate the
  557. field length  */
  558.                 sprintf ( format, "%%%ds\n", length );    /* Make a format
  559. string.       */
  560.  
  561.  
  562.  
  563.                 printf ( format, *ch_pp );                /* Print line of
  564. verse, using  */
  565.                 }                                         /* generated format
  566. string     */
  567.         printf( "\n" );
  568.         }
  569.  
  570. /* ----------------------------------------- */
  571.  
  572.   If you cheated and looked at my example before even attempting
  573.         to have a go, you must pay the penalty and explain fully why
  574.         there are THREE "%" signs in the line which starts with a call
  575.         to the sprintf function. It's a good idea to do this anyway!
  576.  
  577.  
  578.   
  579.  
  580.  
  581.  
  582. So much for printf(). Lets examine it's functional opposite - scanf(),
  583.  
  584.         Scanf is the family of functions used to input from the outside world  and to perform internal format conversions from character strings to binary numbers. Refer to the entry scanf(3S) in the Programmer  Reference Manual. ( Just a few pages further on from printf. )
  585.  
  586.   The "Important Point to Note" for the scanf family is that the
  587.  arguments to the function are all POINTERS. The format string has to  be passed in to the function using a pointer, simply because this  is the way 'C' passes strings, and as the function itself has to store  its results into your program it ( the scanf function ) has to "know" where you want it to put them.
  588.